<?php
/**
 * 学生控制器
 *
 * @package    app
 * @version    1.0
 * @author     Ray 33705910@qq.com
 * @license    MIT License
 * @copyright  2013 - 2015 Ray
 * @link       http://wangxiaolei.cn
 */

/**
 * 本控制器主要用于：
 * 1.
 * @package  app
 * @extends  Controller
 */
namespace admin;

class Controller_Student extends  \Controller_BaseController {

	public $template = 'edu/template';

	public function action_index(){
		$params = array(
  			'title' => '学生中心——学生管理',
  			'menu' => ''
  		);

		$params['items'] = \Model_Student::getItems('*', array('is_delete' => 0), array('people', 'grade'));
		$params['grades'] = \Model_Grade::getItems();


  		\View::set_global($params);
		$this->template->content = \View::forge("edu/member/students");
	}

	/**
	* 查看某学习记录
	*
	* @return
	*/
	public function action_view($id){
		if( ! $id){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 10)));
			}
		}

		$student = \Model_Student::find($id);
		if( ! $student){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 11)));
			}
		}

		if(\Input::is_ajax()){
			$student->people->birthday = date('Y-m-d H:i', $student->people->birthday);
			die(json_encode(array('status' => 'succ', 'msg' => '', 'errcode' => 0, 'data' => $student->to_array())));
		}
	}

	/**
	* 新增一个学生
	*
	* @return
	*/
	public function action_create(){

		if(\Input::method() == 'POST'){
			$data = \Input::post();
			$data['is_delete'] = 0;

			$id = \Auth::create_user('student' . time(), time(), $data['email'] ? $data['email'] : time() . '@test.com', 1);
			$data['user_id'] = $id;
			$data['birthday'] = strtotime($data['birthday']);
			\Model_People::forge($data)->save();

			$data['status'] = 'NONE';
			$teacher = \Model_Student::forge($data);

			if($teacher->save()){
				\Response::redirect('/admin/student');
			}
		}
	}

	/**
	* 编辑学生资料
	*
	* @param $id int 学生ID
	* @return
	*/
	public function action_edit($id){
		if( ! $id){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 10)));
			}
		}
		
		$data = \Input::post();

		$student = \Model_Student::find($id);
		if( ! $student){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 11)));
			}
		}

		$data['birthday'] = strtotime($data['birthday']);
		$people = \Model_People::find($student->user_id);
		$people->set($data);
		$people->save();

		$student->set(\Input::post());
		if($student->save()){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'succ', 'msg' => '操作成功', 'errcode' => 0)));
			}
			\Response::redirect("/admin/student");
		}else{
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '操作失败', 'errcode' => 20)));
			}
		}
	}

	/**
	* 删除一个学生
	*
	* @param $id int 学生ID
	* @return
	*/
	public function action_delete($id){
		if( ! $id){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 10)));
			}
		}

		$student = \Model_Student::find($id);
		if( ! $student){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 11)));
			}
		}

		$student->is_delete = 1;
		if($student->save()){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'succ', 'msg' => '', 'errcode' => 0)));
			}
		}else{
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '操作失败', 'errcode' => 10)));
			}
		}
	}

	/**
	* 获取学习记录
	*
	* @return
	*/
	public function action_learn_records(){
		$params = array(
  			'title' => '学生中心——所有学生学习记录',
  			'menu' => ''
  		);

  		$params['students'] = \Model_Student::getItems();

  		$params['teachers'] = \Model_Teacher::getItems();

  		$where = array();
  		if(\Input::get('student_id', false)){
  			$where['student_id'] = \Input::get('student_id');
  		}
  		if(\Input::get('teacher_id', false)){
  			$where['teacher_id'] = \Input::get('teacher_id');
  		}
  		if(\Input::get('course_id', false)){
  			$where['course_id'] = \Input::get('course_id');
  		}
		$params['items'] = \Model_LearnRecord::getItems('*', $where, array('teacher', 'course', 'student'));

  		\View::set_global($params);
		$this->template->content = \View::forge("edu/member/learn_records");
	}

	/**
	* 删除学习记录
	*
	* @return
	*/
	public function action_learn_delete($id){
		if( ! $id){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 10)));
			}
		}

		$record = \Model_LearnRecord::find($id);
		if( ! $record){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 11)));
			}
		}

		if($record->delete()){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'succ', 'msg' => '', 'errcode' => 0)));
			}
		}else{
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '操作失败', 'errcode' => 10)));
			}
		}
	}

	/**
	* 创建学习记录
	*
	* @return
	*/
	public function action_learn_create(){
		if(\Input::method() == 'POST'){
			$data = \Input::post();

			$data['status'] = 'NONE';
			$data['learn_start'] = strtotime($data['learn_start']);
			$data['learn_end'] = strtotime($data['learn_end']);
			$record = \Model_LearnRecord::forge($data);

			if($record->save()){
				if(\Input::is_ajax()){
					die(json_encode(array('status' => 'succ', 'msg' => '', 'errcode' => 0, 'data' => \Input::post('index'))));
				}
				\Response::redirect('/admin/student/learn_records');
			}
		}
	}

	/**
	* 查看某学习记录
	*
	* @return
	*/
	public function action_learn_view($id){
		if( ! $id){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 10)));
			}
		}

		$record = \Model_LearnRecord::find($id);
		if( ! $record){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 11)));
			}
		}

		if(\Input::is_ajax()){
			$record->student;
			$record->teacher;
			$record->course;
			$record->learn_start = date('Y-m-d H:i', $record->learn_start);
			$record->learn_end = date('Y-m-d H:i', $record->learn_end);
			die(json_encode(array('status' => 'succ', 'msg' => '', 'errcode' => 0, 'data' => $record->to_array())));
		}
	}

	/**
	* 编辑学习记录
	*
	* @param $id int 学习记录ID
	* @return
	*/
	public function action_learn_edit($id){

		if( ! $id){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 10)));
			}
		}

		$data = \Input::post();

		$learn = \Model_LearnRecord::find($id);
		if( ! $learn){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '无效的参数', 'errcode' => 11)));
			}
		}

		$data['learn_start'] = strtotime($data['learn_start']);
		$data['learn_end'] = strtotime($data['learn_end']);

		$learn->set($data);
		if($learn->save()){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'succ', 'msg' => '操作成功', 'errcode' => 0)));
			}
			\Response::redirect('/admin/student/learn_records');
		}else{
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '操作失败', 'errcode' => 20)));
			}
		}
	}

	/**
	* 导入学习记录
	*
	* @return
	*/
	public function action_learn_import(){

		$params = array(
  			'title' => '学生中心——导入学习记录',
  			'menu' => ''
  		);
		//'/uploads/files/a.xls'

		if(\Input::method() == 'POST'){
			$file = DOCROOT . \Input::post('file');
			$content = \tools\ExcelTools::importByExcel($file);

			$items = array();
			$current = current($content);
			foreach ($content as $key => $value) {
				if($current == $value){
					continue;
				}

				$sid = 0;$cid = 0; $tid = 0;
				$stu_select = array();
				$cou_select = array();
				$tea_select = array();

				//比对学生
				$where = "CONCAT(p.first_name,p.last_name) = '{$value[1]}'";
				if($value[0]){
					$where .= " AND no = '{$value[0]}'";
				}
				$sql = "SELECT s.id, s.no, p.first_name, p.last_name, CONCAT(p.first_name,p.last_name) as name FROM students AS s LEFT JOIN peoples AS p ON s.user_id = p.user_id WHERE is_delete = 0 AND {$where};";
				$stus = \DB::query($sql)->execute()->as_array();
				if($stus){
					if(count($stus) > 1){
						foreach ($stus as $stu) {
							array_push($stu_select, array('id' => $stu['id'], 'name' => "{$stu['first_name']}{$stu['last_name']}(学号：{$stu['no']})"));
						}
						$sid = -1;
					}else{
						$sid = current($stus)['id'];
					}
				}

				//比对课程
				$courses = \Model_Course::query()
					->related('grade')
					->where('name', $value[3]);
					
				if($value[2]){
					$courses->where('grade.name', $value[2]);
				}

				$courses = $courses->get();
				if($courses){
					if(count($courses) > 1){
						foreach ($courses as $course) {
							array_push($cou_select, array('id' => $course->id, 'name' => "{$course->name}({$course->grade->name})"));
						}
						$cid = -1;
					}else{
						$cid = current($courses)->id;
					}
				}

				//比对教师
				$sql = "SELECT t.id, p.phone, p.first_name, p.last_name, CONCAT(p.first_name,p.last_name) as name FROM teachers AS t LEFT JOIN peoples AS p ON t.user_id = p.user_id WHERE CONCAT(p.first_name,p.last_name) = '{$value[4]}'";
				$teachers = \DB::query($sql)->execute()->as_array();

				if($teachers){
					if(count($teachers) > 1){
						foreach ($teachers as $teacher) {
							array_push($tea_select, array('id' => $teacher['id'], 'name' => "{$teacher['name']}({$teacher['phone']})"));
						}
						$tid = -1;
					}else{
						$tid = current($teachers)['id'];
					}
				}

				//组合数据
				$data = array(
					'index' => count($items),
					'student_id' => $sid,
					'course_id' => $cid,
					'teacher_id' => $tid,
					'student_name' => $value[1],
					'course_name' => $value[3],
					'teacher_name' => $value[4],
					'learn_start_date' => gmdate('Y-m-d H:i:s', ($value[5] - 25569) * 24 * 60 * 60),
					'learn_end_date' => gmdate('Y-m-d H:i:s', ($value[6] - 25569) * 24 * 60 * 60),
					'learn_start' => strtotime(gmdate('Y-m-d H:i:s', ($value[5] - 25569) * 24 * 60 * 60)),
					'learn_end' => strtotime(gmdate('Y-m-d H:i:s', ($value[6] - 25569) * 24 * 60 * 60)),
					'remark' => count($value) > 7 ? $value[7]  :  '',
					'students' => $stu_select,
					'courses' => $cou_select,
					'teachers' => $tea_select
				);
				array_push($items, $data);

				/*$record = \Model_LearnRecord::forge($data);
				$record->save();*/
			}

			\Cookie::delete('import_excel_data_by_student_learn_records');
			\Cookie::set('import_excel_data_by_student_learn_records', serialize($items), 60 * 60 * 24 * 1);
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'succ', 'msg' => '', 'data' => $items)));
			}

		}
		
		\View::set_global($params);
		$this->template->content = \View::forge("edu/member/learn_records");
	}

	/**
	* 学生选课
	*
	* @return
	*/
	public function action_course($sid = 0){

		if( ! $sid){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '请先选择要选课的学生', 'errcode' => 0)));
			}
			die('请先选择要选课的学生');
		}

		$params = array(
  			'title' => '学生中心——学生选课',
  			'menu' => ''
  		);

		if(\Input::method() == 'POST'){
			$stu = \Model_Student::find($sid);
			$data = \Input::post();
			foreach ($data['courses'] as $key => $value) {
				$item = array(
					'student_id' => $sid,
					'member_id' => $stu->family_id,
					'course_id' => $value
				);
				$course = \Model_StudentCourse::forge($item);
				$course->save();
			}
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'succ', 'msg' => '', 'errcode' => 0)));
			}
		}

  		\View::set_global($params);
		$this->template->content = \View::forge("edu/member/learn_records");
	}

	/**
	* 学生选课
	*
	* @return
	*/
	public function action_courses($sid = 0){

		if( ! $sid){
			if(\Input::is_ajax()){
				die(json_encode(array('status' => 'err', 'msg' => '请先选择要选课的学生', 'errcode' => 0)));
			}
			die('请先选择要选课的学生');
		}

  		$where = array();  		
		$items = \Model_StudentCourse::query()
				->related(array('teacher', 'course', 'course.grade', 'course.term', 'student'))
				->where('student_id', $sid)
				->get();

		if(\Input::is_ajax()){
			$data = array();
			foreach ($items as $key => $value) {
				$item = array(
					'id' => $value->id,
					'course' => "{$value->course->name}({$value->course->grade->name}{$value->course->term->name})",
					'created' => date('Y-m-d H:i:s', $value->created_at)
				);
				array_push($data, $item);
			}			
			die(json_encode(array('status' => 'succ', 'msg' => '', 'errcode' => 0, 'data' => $data)));
		}
	}

}
